package com.wyh.security.gfive.service;

import cn.hutool.jwt.Claims;
import com.wyh.common.enums.ResultCodeEnum;
import com.wyh.common.utils.StringUtils;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.wyh.common.code.redis.RedisCache;
import com.wyh.common.constant.CacheConstants;
import com.wyh.common.constant.Constants;
import com.wyh.common.exception.CustomException;
import com.wyh.common.utils.TokenUtils;
import com.wyh.common.utils.uuid.IdUtils;
import com.wyh.domain.dto.gfive.LoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

import java.util.HashMap;

import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.wyh.common.utils.TokenUtils.createToken;


@Component
public class TokenService {

    private static final long MILLIS_MINUTE_TEN = 20 * 60 * 1000L;
    private static final Long MILLIS_MINUTE = 60 * 1000L;
    @Autowired
    private RedisCache redisCache;

    @Value("${token.expireTime}")
    private int expireTime;



    // 创建登录令牌
    public String loginCreateToken(LoginUser loginUser) {

        loginUser.setLoginTime(System.currentTimeMillis());

        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        String token = IdUtils.fastUUID();
        loginUser.setToken(token);
        //设置用户信息设置缓存
        refreshToken(loginUser);
        //设置用户信息token
        Map<String, Object> claims = new HashMap<>();
        claims.put(Constants.LOGIN_USER_KEY, token);

        return createToken(claims);
    }

    public void refreshToken(LoginUser loginUser) {
        loginUser.setLoginTime(System.currentTimeMillis());
        loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
        // 根据uuid将loginUser缓存
        String userKey = getTokenkey(loginUser.getToken());
        redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
    }

    private String getTokenkey(String uuid) {
        return CacheConstants.LOGIN_TOKEN_KEY + uuid;
    }

    /**
     * 获取用户身份信息
     */
    public LoginUser getLoginUser(HttpServletRequest request) {

        // 获取请求携带的令牌
        String token = getToken(request);



        if (StringUtils.isNotEmpty(token)) {
            // 解析token获取claims
            try {
                Claims claims = TokenUtils.getClaimsFromToken(token);
                JsonObject claimsJson = JsonParser.parseString(String.valueOf(claims)).getAsJsonObject();
                // 从claims中获取token
                String uuid = claimsJson.getAsJsonObject("data").get(Constants.LOGIN_USER_KEY).getAsString();
                String userKey = getTokenkey(uuid);
                // 从缓存中获取loginUser
                LoginUser user = redisCache.getCacheObject(userKey);
                return user;

            } catch (Exception e) {
                throw new CustomException(ResultCodeEnum.TOKEN_INVALID_ERROR);
            }
        }
        return null;


    }

    /**
     * 设置用户身份信息
     */
    public void setLoginUser(LoginUser loginUser) {
        if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
            refreshToken(loginUser);
        }
    }

    /**
     * 删除用户身份信息
     */
    public void delLoginUser(String token) {
        if (StringUtils.isNotEmpty(token)) {
            String userKey = getTokenkey(token);
            redisCache.deleteObject(userKey);
        }
    }

    /**
     * 验证令牌有效期，相差不足20分钟，自动刷新缓存
     *
     * @param loginUser
     * @return 令牌
     */
    public void verifyToken(LoginUser loginUser) {
        long expireTime = loginUser.getExpireTime();
        long currentTime = System.currentTimeMillis();
        if ( expireTime -currentTime <= MILLIS_MINUTE_TEN) {
            refreshToken(loginUser);
        }
    }

    private String getToken(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
            token = token.replace(Constants.TOKEN_PREFIX, "");
            return token;
        }
      return null;
    }
}
